<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>

<head>
    <title id="window-title"></title>
    <link rel="stylesheet" href="css/Details.css">
</head>
<body>
<%@include file="header.jsp" %>
<section>
    <div id="header">
        <div id="product-intro">
        </div>
    </div>
    <div id="section">
        <div class="navigation">
            <a class="introduce active">商品介绍</a>
            <a class="evaluate">商品评价</a>
            <a class="QandA">商品问答</a>
        </div>
        <div id="store_box">
        </div>
        <div id="item">
        </div>
        <div id="comment_show">
            <div class="navigation">
                <span class="assess">商品评价</span>
            </div>
            <div id="comment_user">
                <ul class="commodity_comment">
                </ul>
            </div>
        </div>
        <div id="questions_and_answers">
            <div id="questions—header">
                <p class="question">商品问答</p>
                <div id="answers_section">
                    心中疑惑就问问买过此商品的同学吧~
                    <button onclick="openModal()">我要提问</button>
                </div>
            </div>
            <div id="myModal" class="modal">
                <div class="modal-content">
                    <div id="header_problem">
                        <span id="problem_head">提问</span>
                        <span class="textarea-tips">您的问题将推送给已购用户，TA们会帮您解答</span>
                        <span class="close" onclick="closeModal()">&times;</span>
                    </div>
                    <div class="ask-textarea">
                        <textarea class="p-txa" id="comment" cols="4" rows="10" placeholder="请输入您的问题吧~"></textarea>
                        <span><em class="p-txtnum">0</em> / 50</span>
                    </div>
                    <div class="bt-wrap">
                        <input id="askAnswerAnonymous" class="pj" type="checkbox" checked="checked">
                        <label for="askAnswerAnonymous">匿名提问</label>
                        <a class="btn-confirm">发布</a>
                        <a href="#" class="btn-cancel" onclick="closeModal()">取消</a>
                    </div>
                </div>
            </div>
            <div id="question_section">
            </div>
        </div>
    </div>
</section>
<%@include file="footer.jsp" %>
</body>
</html>
<script src="js/jquery.min.js"></script>
<script>
    window.onload = function () {
        const params = new URLSearchParams(window.location.search);
        const commodityId = params.get("commodityId");
        initParams()
        initWindow()
        getCommodityId(commodityId); // 页面优化
        getAnswerAndProblem(commodityId); // 评论
    }
    $(".introduce").click(function () {
        $("#comment_show, #questions_and_answers").fadeIn("show");
        $("#item").fadeIn("show");
        $("#comment_show").css({
            "margin-top": "5px"
        })
        $(".introduce").removeClass("active");
        $(".evaluate").removeClass("active");
        $(".QandA").removeClass("active");
        $(this).addClass("active");
    });

    $(".evaluate").click(function () {
        $("#item, #questions_and_answers").fadeOut("show");
        $("#comment_show").fadeIn("show");
        $("#comment_show").css({
            "margin-top": "-50px"
        })
        $(".introduce").removeClass("active");
        $(".evaluate").removeClass("active");
        $(".QandA").removeClass("active");
        $(this).addClass("active");
    });

    $(".QandA").click(function () {
        $("#item, #comment_show").fadeOut("show");
        $("#questions_and_answers").fadeIn("show");
        $(".introduce").removeClass("active");
        $(".evaluate").removeClass("active");
        $(".QandA").removeClass("active");
        $(this).addClass("active");
    });

    function openModal() {
        $("#myModal").show();
    }

    function initWindow() {
        var clientWidth = document.documentElement.clientWidth;
        var bodys = document.getElementsByTagName('body')[0];
        bodys.style.cssText = "background-size: " + clientWidth + "px auto;";
    }

    function closeModal() {
        $("#myModal").hide();
    }


    $(document).ready(function () {
        $('.p-txa').on('input', function () {
            var text = $(this).val();
            var byteCount = text.length; // 计算字节数
            if (byteCount > 50) {
                alert("字符数不能超过50！");
                this.value = this.value.slice(0, 50); // 缩减到50个字符
                text = $(this).val();
            }
            byteCount = text.length;
            $('.p-txtnum').text(byteCount); // 更新p-txtnum中的字节数
        });
        let a = 0;
        $(document).on('click', '.toggle-answer', function () {
            const $answers = $(this).siblings('.answer'); // 获取当前问题的所有答案。
            a++;
            $answers.toggle(500); // 切换当前问题的答案显示/隐藏状态。
            if (a == 1) {
                $(this).text("收起回答 ↑");
            } else {
                $(this).text("继续查看回答 ↓");
                a = 0;
            }
        });
        // 访问次数和浏览历史
        let isFirstVisit = true;
        if (sessionStorage.getItem('isFirstVisit') === null) {
            sessionStorage.setItem('isFirstVisit', '1');
            const params = new URLSearchParams(window.location.search);
            const commodityId = params.get("commodityId");
            let user = localStorage.getItem("userJson");
            user = eval('(' + user + ')');
            const userId = user.userId;
            $.ajax({
                type: "POST",
                url: "commodity/addNumberOfViews",
                data: {
                    commodityId: commodityId
                },
                success: function (res) {
                },
                error: function () {
                    alert("error")
                }
            })
            $.ajax({
                type: "post",
                url: "browsingHistory/addBrowsingHistory",
                data: {
                    userId: userId,
                    commodityId: commodityId
                },
                success: function (res) {
                    console.log(res)
                },
                error: function () {
                    alert("error")
                }
            })
        } else {
            isFirstVisit = false;
        }
        // 刷新页面时不增加计数器的值
        $(window).on('beforeunload', function () {
            if (isFirstVisit) {
                sessionStorage.setItem('isFirstVisit', '1');
            }
        });
    });

    function preventDefault() {
        alert("请登录后购买");
    };
    const window_title = $("#window-title");
    const product_intro = $("#product-intro");
    const item = $("#item");
    const commodity_comment = $(".commodity_comment");
    const question_section = $("#question_section");
    let htmlComment = "";
    let html = "";
    let htmlAnswer = "";
    let htmlProductIntro = "";
    let htmlDetails = "";

    function getCommodityId(commodityId) {
        $.ajax({
            type: "POST",
            url: "commodity/getCommodityId",
            data: {
                commodityId: commodityId
            },
            success: function (res) {
                console.log(res)
                if (res.msg == "success") {
                    window_title.text("旗木宠物-商品详情-" + res.data.commodityName);
                    htmlProductIntro =
                        "<div id=\"left_img\">" +
                        "<img src='../" + res.data.commodityImgList[0].commodityImg + "' >" +
                        "</div><div id=\"right_title\"><ul>" +
                        "<li id=\"commodity_title\">" + res.data.commodityName + "</li><li><div>" +
                        "<span class=\"commodity_price\">商品单价：</span>" +
                        "<span class=\"commodity_price_number\">" + '￥' + (res.data.commodityPrice * 0.9).toFixed(2) + "</span><br>" +
                        "<span class=\"commodity_original_price\">市场价：</span>" +
                        "<span class=\"commodity_original_number\">" + '￥' + res.data.commodityPrice + "</span>" +
                        "</div></li><li id=\"business\">" +
                        "<span>业务：</span><span>可配货</span>|" +
                        "<span>可配送全球</span>|<span>7天价保</span>|" +
                        "<span>包邮</span>|<br><br><span>预约送货</span>|" +
                        "<span>部分收货</span>|<span>送货上门</span></li>" +
                        "<li class=\"brand\">" +
                        "<span class=\"title_commodity\">商品品牌：</span>" +
                        "<span class=\"commodity_brand\">" + res.data.commodityBrand + "</span>" +
                        "</li><li class=\"brand\"><span class=\"title_commodity\">商品浏览次数：</span>" +
                        "<span id=\"number_of_views\">" + res.data.numberOfViews + "</span></li>" +
                        "<li>";
                    let user = localStorage.getItem("userJson");
                    user = eval('(' + user + ')');
                    if (user != null) {
                        htmlProductIntro += "<button class='concern'>＋关注</button><a href='buyCommodity.jsp?commodityId=" + res.data.commodityId + "' id=\"purchase\">购买</a></li></ul></div>";
                    } else {
                        htmlProductIntro += "<button class='concern'>＋关注</button><a id=\"purchase\" onclick='preventDefault()'>购买</a></li></ul></div>";
                    }
                    product_intro.append(htmlProductIntro)
                    const details = res.data.commodityDetails;
                    const desc = details.split(",");
                    var info = desc.map(function (item) {
                        return item.split("：")[1];  // 对每个元素使用冒号分割，并返回第二个元素
                    });
                    htmlDetails =
                        "<div class=\"p-parameter\">" +
                        "<div class=\"brean\" title='" + res.data.commodityBrand + "'>品牌：<span>" + res.data.commodityBrand + "</span></div><ul>";
                    for (let i = 0; i < desc.length; i++) {
                        htmlDetails += "<li title='" + info[i] + "'>" + desc[i] + "</li>";
                    }
                    htmlDetails += "</ul></div>";
                    item.append(htmlDetails);
                    for (let i = 1; i < res.data.commodityImgList.length; i++) {
                        html = "<img src=\"../" + res.data.commodityImgList[i].commodityImg + "\">";
                        item.append(html);
                    }
                    for (let i = 0; i < res.data.commentList.length; i++) {
                        htmlComment =
                            "<li style='margin-bottom: 20px'>" +
                            "<img src='../" + res.data.commentList[i].user.headImg + "' class=\"user_img\">" +
                            "<div class=\"user_comment\">" +
                            "<p>" + res.data.commentList[i].user.username + "</p>" +
                            "<p>" + res.data.commentList[i].commentTime + "</p><br>" +
                            "<p>" + res.data.commentList[i].commentContent + "</p>" +
                            "<div class=\"user_commodity_imgs\">";
                        if (res.data.commentList[i].commentImgList.length > 0) {
                            for (let j = 0; j < res.data.commentList[i].commentImgList.length; j++) {
                                htmlComment += "<img src='../" + res.data.commentList[i].commentImgList[j].commentImg + "' class=\"user_commodity_img\">";
                            }
                        }
                        htmlComment += "</div></div></li>";
                        commodity_comment.append(htmlComment);
                        concernStore(res.data.store.storeId, ".concern")
                    }
                    let htmlStore = "";
                    const store_box = $("#store_box");
                    htmlStore =
                        "<ul><li id=\"store_name\">" +
                        "<p class=\"store\">" + res.data.store.storeName + "</p>" +
                        "<a href='' class=\"customer_service\" title=\"联系店家\">💬</a>" +
                        "</li><li id=\"btns\">" +
                        "<a href='store.jsp?storeId=" + res.data.store.storeId + "' class=\"enter\">进店逛逛</a>" +
                        "<a class=\"care\">关注店铺</a>" +
                        "</li></ul>";
                    store_box.append(htmlStore);
                    concernStore(res.data.store.storeId, ".care");
                }
                $(".concern").click(function () {
                    concernTotal(res.data.commodityId, ".concern")
                })
                $(".care").click(function () {
                    concernTotal(res.data.store.storeId, ".care")
                })
            },
            error: function () {
                alert("error");
            }
        })
    }

    function getAnswerAndProblem(commodityId) {
        $.ajax({
            type: "post",
            url: "answerProblem/getAnswerProblemByCommodityId",
            data: {
                commodityId: commodityId
            },
            success: function (res) {
                console.log(res)
                if (res.msg == "success") {
                    for (let i = 0; i < res.data.length; i++) {
                        htmlAnswer =
                            "<div class=\"askAnswer-item\">" +
                            "<div class=\"ask\">" +
                            "<label class=\"label_problem\">问</label>" +
                            "<p class=\"p_problem\">" + res.data[i].answerContent + "</p>" +
                            "<span class=\"user_time\">" + res.data[i].user.username + " " + res.data[i].answerProblemTime + "</span>" +
                            "</div>" +
                            "<div class=\"ask_answer\">" +
                            "<ul class=\"ul_ask\">" +
                            "<li class=\"li_answer\">" +
                            "<label class=\"label_answer\">答</label>" +
                            "</li>";
                        for (let j = 0; j < res.data[i].answer.length; j++) {
                            if (j == 0) {
                                htmlAnswer +=
                                    "<li class=\"li_answer_time\">" +
                                    "<p class=\"p_answer\">" + res.data[i].answer[j].answerContent + "</p>" +
                                    "<span class=\"user_time\">" + res.data[i].answer[j].user.username + " " + res.data[i].answer[j].answerProblemTime + "</span>" +
                                    "</li>";
                            } else {
                                htmlAnswer +=
                                    "<li class=\"li_answer_time answer\">" +
                                    "<p class=\"p_answer_n\">" + res.data[i].answer[j].answerContent + "</p>" +
                                    "<span class=\"user_time\">" + res.data[i].answer[j].user.username + " " + res.data[i].answer[j].answerProblemTime + "</span>" +
                                    "</li>";
                            }
                        }
                        htmlAnswer += "<span class=\"toggle-answer\"></span></ul></div></div><br>";
                        question_section.append(htmlAnswer)
                        $(".toggle-answer").text("继续查看回答 ↓");
                        $(".answer").hide();
                    }
                }
            },
            error: function () {
                alert("error")
            }
        })
    }

    $(".btn-confirm").click(function () {
        const comment = $("#comment").val();
        const commodityId = getUrlParams("commodityId");
        let user = localStorage.getItem("userJson");
        let userId;
        user = eval('(' + user + ')');
        if (user != null) {
            userId = user.userId;
        } else {
            alert("请登录后，再提问！");
            return;
        }
        $.ajax({
            type: "POST",
            url: "answerProblem/addAnswerProblem",
            data: {
                answerContent: comment,
                isProblem: 1,
                answerProblemId: "",
                commodityId: commodityId,
                userId: userId
            },
            success: function (res) {
                if (res == "success") {
                    location.reload();
                } else if (res == "fail") {
                    alert("提问失败")
                }
            },
            error: function () {
                alert("error")
            }
        })
    })

    //初始化url参数
    function initParams() {
        if (getUrlParams('date') == null) {
            date = "0";
        } else {
            date = getUrlParams('date');
        }
        if (getUrlParams('brand') == null) {
            brand = "0";
        } else {
            brand = getUrlParams('brand');
        }
        if (getUrlParams('area') == null) {
            area = "0";
        } else {
            area = getUrlParams('area');
        }
        if (getUrlParams('hall') == null) {
            hall = "0";
        } else {
            hall = getUrlParams('hall');
        }
        if (getUrlParams('page') == null) {
            page = "1";
        } else {
            page = getUrlParams('page');
        }
    }

    //获取url参数
    function getUrlParams(name) { // 不传name返回所有值，否则返回对应值
        var url = window.location.search;
        if (url.indexOf('?') == 1) {
            return false;
        }
        url = url.substr(1);
        url = url.split('&');
        var name = name || '';
        var nameres;
        // 获取全部参数及其值
        for (var i = 0; i < url.length; i++) {
            var info = url[i].split('=');
            var obj = {};
            obj[info[0]] = decodeURI(info[1]);
            url[i] = obj;
        }
        // 如果传入一个参数名称，就匹配其值
        if (name) {
            for (var i = 0; i < url.length; i++) {
                for (const key in url[i]) {
                    if (key == name) {
                        nameres = url[i][key];
                    }
                }
            }
        } else {
            nameres = url;
        }
        // 返回结果
        return nameres;
    }

    function concernStore(id, el) {
        let user = localStorage.getItem("userJson");
        user = eval('(' + user + ')');
        if (user != null) {
            for (let i = 0; i < user.concernList.length; i++) {
                if (el == ".care") {
                    if (user.concernList[i].storeId == parseInt(id)) {
                        $(".care").addClass("ask-concern");
                        $(".care").text("已关注店铺");
                    }
                } else if (el == ".concern") {
                    if (user.concernList[i].commodityId == parseInt(id)) {
                        $(".concern").addClass("ask-concern");
                        $(".concern").text("已关注");
                    }
                }
            }
        } else {
            alert("请登录后再关注");
        }
    }

    function concernTotal(id, el) {
        let user = localStorage.getItem("userJson");
        user = eval('(' + user + ')');
        let userId = user.userId;
        if (el == ".concern") {
            if ($(".concern").text() == "＋关注") {
                $.ajax({
                    type: "POST",
                    url: "concern/addConcern",
                    data: {
                        userId: userId,
                        commodityId: id
                    },
                    success: function (res) {
                        if (res == "success") {
                            alert("关注成功")
                            window.location.reload();
                        } else if (res == "fail") {
                            alert("关注失败")
                        }
                    },
                    error: function () {
                        alert("error");
                    }
                })
            } else {
                alert("您已关注此商品")
            }
        } else if (el == ".care") {
            if ($(".care").text() == "关注店铺") {
                $.ajax({
                    type: "POST",
                    url: "concern/addConcern",
                    data: {
                        userId: userId,
                        storeId: id
                    },
                    success: function (res) {
                        if (res == "success") {
                            alert("关注成功")
                            window.location.reload();
                        } else if (res == "fail") {
                            alert("关注失败")
                        }
                    },
                    error: function () {
                        alert("error");
                    }
                })
            } else {
                alert("您已关注此商品")
            }
        }
    }

</script>
